// config.js
// ====================== 创建提示框 ======================
// 样式
const style = document.createElement('style');
style.textContent = `
  .collect-overlay {
    position: fixed;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    background: rgba(0, 0, 0, 0.5);
    z-index: 12000 !important;
    display: none;
    justify-content: center;
    align-items: center;
  }
  .collect-message {
    background: white;
    padding: 20px 40px;
    border-radius: 8px;
    box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
    font-size: 16px;
    color: #333;
  }
  .collect-message.success { color: #4CAF50; }
  .collect-message.error { color: #f44336; }
`;
document.head.appendChild(style);

// 提示框元素
const overlay = document.createElement('div');
overlay.className = 'collect-overlay';
const message = document.createElement('div');
message.className = 'collect-message';
overlay.appendChild(message);
document.body.appendChild(overlay);

const href = location.href;

// 获取规格层级结构
function getSpecsStructure() {
    const specs = [];
    const specBlocks = document.querySelectorAll('._3NXAWOJUzREUugpJRuCcub ._1XqP0nf5S-RFJd37xasd3m'); // 规格区块（如颜色、尺寸）
    specBlocks.forEach(block => {
        const title = block.querySelector('.sku-specs-key')?.innerText.trim() || '未知规格'; // 规格名称（如“颜色”）
        const options = Array.from(block.querySelectorAll('._3P3M8kC-R2b7CVzyDYcey5 ._1WyUf92EZP9AZWYGR_qnNX')).map(item => ({
            element: item, // 规格选项的DOM元素
            name: item.querySelector('._3OjFw7gZ4dy_x87FmDKaa2')?.innerText, // 规格值（如“红色”）
        }));
        if(options.length > 0) specs.push({ title, options });
    });
    return specs;
}

// 生成所有可能的组合
function generateCombinations(specs) {
    const combinations = [];
    const backtrack = (currentSpecIndex, currentPath) => {
        if (currentSpecIndex === specs.length) {
            combinations.push([...currentPath]);
            return;
        }
        for (const option of specs[currentSpecIndex].options) {
            currentPath.push({...option, title: specs[currentSpecIndex].title});
            backtrack(currentSpecIndex + 1, currentPath);
            currentPath.pop();
        }
    };
    backtrack(0, []);
    return combinations;
}

// 控制提示框显示/隐藏的函数
function showMessage(text, isSuccess = true) {
    message.className = `collect-message ${isSuccess ? 'success' : 'error'}`;
    message.textContent = text;
    overlay.style.display = 'flex';
}

function hideMessage() {
    overlay.style.display = 'none';
}

const PDD_CONFIG = {
    // 通用配置（适用于所有pdd页面）
    common: {
        matches: ["*://*.yangkeduo.com/*"], // 匹配所有pdd页面
        buttonStyle: {
            zIndex: 1000,
            minWidth: '100px',
            height: '50px',
            padding: '5px 20px',
            background: '#e02e24',
            fontSize: '20px',
            borderRadius: '5px',
            color: 'white',
            border: 'none',
            cursor: 'pointer'
        },
    },

    // 不同页面类型的独立配置
    pages: [
        {
            // 匹配所有pdd页面
            name: "pdd详情页",
            // 通过 URL 或 DOM 特征识别页面类型
            condition: {
                urlPattern: "*://mobile.yangkeduo.com", // URL 匹配规则
                // 或通过 DOM 特征识别（如页面中存在特定元素）
                domSelector: "", // 仅当该元素存在时生效
            },
            cardSelector: "html", // 商品卡片选择器
            extractor: async () => {
                const buyByOneself = document.querySelector('.Qzax7E1wzXu0b0pE0Z_Cm._1rkc8zzDp2cXE8Z4VajJtP') || document.querySelector('.Qzax7E1wzXu0b0pE0Z_Cm')
                if(buyByOneself) {
                    buyByOneself.click();
                    await new Promise(resolve => setTimeout(resolve, 200)); // 等待弹窗弹起
                    const specs = getSpecsStructure();
                    const combinations = generateCombinations(specs);
                    const results = [];
                    for (let i = 0; i < combinations.length; i++) {
                        const combination = combinations[i];
                        let isValid = true;
                        let imgUrl = ''
                        // 依次点击当前组合的规格
                        for(let i = 0; i < combination.length; i++) {
                            const option = combination[i];
                            try {
                                const isExist = option.element.classList.contains('_2bBCR7qtAkTb0g-7s9T70v')
                                if(!isExist) {
                                    option.element.click(); // 模拟点击
                                }
                                await new Promise(resolve => setTimeout(resolve, 200)); // 等待价格更新
                                imgUrl = document.querySelector('.nxbx3dADVbsLmJ_JdPeNU img')?.src || imgUrl
                                // 检查是否可选（如灰色不可点击）
                                if (option.element.classList.contains('isDisabled--x_T2h1sh') && i === combination.length -1) {
                                    isValid = false;
                                    break;
                                }
                            } catch (error) {
                                isValid = false;
                                break;
                            }
                        }

                        // 如果组合有效，记录价格
                        if (isValid) {
                            const price =
                                document.querySelector('._2Icr8_BZkkAbiOv6DgNMfs')?.innerText.replace('券前¥', '') ||
                                document.querySelector('._27FaiT3NZbuN4FyBIxoGve')?.innerText.replace('¥', '');
                            const specs = {}
                            for(let i = 0; i < combination.length; i++) {
                                specs[combination[i].title] = combination[i].name
                            }
                            // const specNames = combination.map(opt => opt.name);
                            results.push({ specs, price, imgUrl });
                        }

                        // 更新进度提示
                        showMessage(`已采集 ${i + 1}/${combinations.length} 种组合...`);
                    }

                    let imageTexts = document.querySelectorAll('._1fBWnMAgRYBD7MRcpC0tWR img')
                    let imageText = []
                    for (let i = 0; i < imageTexts.length; i++) {
                        if(i + 1 !== imageTexts.length) {
                            const imgUrl = imageTexts[i]?.getAttribute("src") || imageTexts[i]?.getAttribute("data-src")
                            imageText.push(imgUrl)
                        }
                    }
                    imageText = [...new Set(imageText)];

                    document.querySelector('._1PJkHLAgo8znl9b6WRjv18._1ifQun1HbSuXsG7u9RZfyZ').click()

                    return {skus: results, imageTexts: imageText};
                }
            },
            buttonStyle: {
                position: 'fixed',
                bottom: '50px',
                left: '10px'
            },
        },
    ],
};
